define(
	[
		'require'
	],
	function(require){
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail", "businessCenter"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			clickTimePoint: Ember.computed.oneWay('controllers.businessDetail.clickTimePoint'),

			businessIdChange: Ember.observer("business.id", function(){
				this.set('keyWord', '');
			}),

			timePointLisenterEvent:Ember.computed("clickTimePoint", function(key, value){
				var view = Broada.getView("businessTimeRangesTopo");
				if(this.get("clickTimePoint") != null){
					var date = new Date(this.get("clickTimePoint"));
					if(typeof view != "undefined"){
						var range = view.getTimeRange().endDate - view.getTimeRange().startDate;	
						if(range == 60000){
							this.set("startDate", date);
							this.set("endDate", new Date(date.getTime()+range));
						}else{
							this.set("startDate", new Date(date-range));
							this.set("endDate", date);
						}
					}
					typeof view != "undefined"?view.set("btnTxt", date?APM.util.formatDate(date, "f"):null):null;
					this.requirePerformances();
				}
			}),

			/*
				列配置
			*/
			columns: Ember.computed(function(){
				var columns = [
					{
						headerText: "交易名称",
						dataKey:"name",
						width: 100,
						ensurePxWidth: true,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								args.$container.addClass("btn-link");
							}
						}
					},
					{
						headerText: "吞吐量",
						dataKey:"performance.system/throughput/total",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "总用户数",
						dataKey:"performance.system/user/unique",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "Apdex",
						dataKey:"performance.system/score/apdex",
						cellFormatter: function(args,colume){
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								if(typeof args.row.data.performance["system/score/apdex"] != "undefined" && typeof args.row.data.apdex_t != "undefined"){
									var data = args.row.data.performance["system/score/apdex"] + "  ["+args.row.data.apdex_t+"]"
									var label = "<label>"+data+"</label>";
									args.$container.append(label);
									return true;
								}else{
									var label = "<label> - </label>";
									args.$container.append(label);
									return true;
								}
							}
						}
					},
					{
						headerText: "不满意的访问数",
						dataKey:"performance.system/apdex/unsatisfied",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "受影响的用户数",
						dataKey:"performance.system/user/unsatisfied",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "响应时间",
						dataKey:"performance.system/response_time/avg",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "最快",
						dataKey:"performance.system/response_time/min",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "最慢",
						dataKey:"performance.system/response_time/max",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "错误数",
						dataKey:"performance.system/error/count",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "成功率",
						dataKey:"performance.system/success/rate",
						cellFormatter: APM.util.indicatorCellFormatter
					}
				];
				if(!this.get("auth.isNormal")){
					columns.push({
						headerText: "操作",
						dataKey:"id",
						width: 130,
						allowSort: false,
						ensurePxWidth: true,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								var ctrl = this.get("controller"),
									data = args.row.data,
									$btnGroup = $('<div class="btn-group"></div>').appendTo(args.$container);

								var ub = $('<button class="btn btn-mini" type="button" title="修改关键交易"><i class="icon-edit"/></button>');

								ub.appendTo($btnGroup).on("click",function(){
									ctrl.set("resourceId", data.id);
									var dialog = Broada.getView("set_trade");
									ctrl.requireResourceApdex();
									dialog.openDialog();
								});

								var cb = $('<button class="btn btn-mini" type="button" title="取消关键交易"><i class="icon-remove"/></button>');
					
								cb.appendTo($btnGroup).on("click",function(){
									confirmDialog('确定要取消关键交易吗？')
									.then(function() {
										ctrl.cancelKeyTrade(data.id);
									});
									
								});

								var ab = $('<button class="btn btn-mini" type="button" title="配置阈值"><i class="icon-cog"/></button>');
					
								ab.appendTo($btnGroup).on("click",function(){
									var configThresholdsView = Broada.getView("businessConfigThresholdView");
									configThresholdsView.set("targetResource", {targetId: data.id, targetName: data.name});
									configThresholdsView.requireThreshold(data.id);
									configThresholdsView.openDialog();
								});

								return true;
							}
						}
					});
				}

				return columns;
			}),

			keyTrades: Ember.A(),

			startDate: null,

			endDate: null,

			/*
				向服务端请求某一小时内的详细性能数据
			*/
			requirePerformances: function(){
				var ctrl = this;
				var appId = this.get("business.id");

				var pageIndex = this.get("pageIndex");

				var startDate = this.get("startDate"),
					endDate = this.get("endDate");

				var params = {
					appId: appId,
					keyWord: this.get("keyWord"),
					startDate: +startDate,
					endDate: +endDate
				};
				//开发调试模式参数
				if( isLocalDebugModel ){
					delete params.startDate;
					delete params.endDate;
					delete params.keyWord;
				}

				return this.store.ajax("GET", "keytrades/performances/subtotal", params)
				.then(function(response){
					var keyTrades = Ember.A(response['result']);

					keyTrades.forEach(function(trade){
						trade.performance = trade.performance||{};
					});

					if (keyTrades.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);
					}else{
						ctrl.set("pageIndex",null);
						ctrl.set("pageSize",null);
						ctrl.set("totalRows",null);
					}
					
					ctrl.set("keyTrades",keyTrades);
					return response;
				});
			},

			requireResourceApdex: function() {
				var ctrl = this,
					resourceId = this.get("resourceId");
				return this.store.ajax("GET", "resource/"+resourceId+"/apdex_t", {
					resId : resourceId
				})
				.then(function(response){
					var keyTrade = Ember.A(response['result']);
					ctrl.set("tradeName", keyTrade.name);
					ctrl.set("tradeUri", keyTrade.uri);
					ctrl.set("apdex_t", keyTrade.apdex_t);
					return response;
				});
			},

			cancelKeyTrade: function(resourceId) {
				var ctrl = this;
				this.store.ajax("PUT", "resource/"+resourceId,{
					"resourceId" : resourceId
				}).then(function(response){
					alertTip("取消成功！", "success");
					ctrl.requirePerformances();
				});
			},

			actions: {
				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requirePerformances();
				},

				gridSorted:function(e, data, view){
					view.ensureControl(false);
				},

				gridCellClicked: function(e, args, view){
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column();
					if (row && (row.type & $.wijmo.wijgrid.rowType.data)) {
						if(column.dataKey == "name"){
							this.transitionToRoute("business.detail.trade", this.get("business"), row.data);
						}
					}
				},

				setTrade: function(){
					var ctrl = this;

					var resourceId = this.get("resourceId");
					var name = this.get("tradeName");
					if(!name){
						this.set("formTip", "交易名称不能为空!");
						return;
					}

					var apdex_t = this.get("apdex_t");
					if (apdex_t && !/^[\d]+$|^\d*\.\d+$/.test(apdex_t)) {
						this.set("formTip", "apdex_t值必须为整数或小数！");
						return;
					}

					this.set("formTip", null);
					
					this.store.ajax("PUT", "resource",{
						"resourceId" : resourceId,
						"name" : name,
						"apdex_t" : apdex_t
					}).then(function(response){
						if(response) {
							alertTip("保存成功！", "success");
							ctrl._actions.closeDialog();

							ctrl.requirePerformances();
							
							ctrl.set("tradeName","");
							ctrl.set("tradeUri", "");
							ctrl.set("apdex_t","");
						} else {
							alertTip("保存失败！", "error");
						}
					});
				},

				closeDialog: function(){
					Broada.getView("set_trade").closeDialog();
				},

				search: function() {
					this.set("pageIndex", 0);
					this.requirePerformances();
				},

				timeRangesChange: function(timeRange){
					this.set("startDate", timeRange.startDate);
					this.set("endDate", timeRange.endDate);
					this.set("pageIndex", 0);
					this.requirePerformances();
				}
			}
		});
		APM.BusinessDetailTradesKeyController = Controller;
		return Controller
	}
);	